import prettytable

from .operator.physical_operator import PhysicalOperator


class Result:
    """
    Result of the execution
    """
    def __init__(self, target_columns=None):
        self.rows = [] # 其实就是返回的各个tuples
        self.target_columns = target_columns

    def add_row(self, row):
        self.rows.append(row)

    def to_pretty_string(self):
        if not self.target_columns:
            return '(Rows 0)'
        field_names = [str(c) for c in self.target_columns]
        p = prettytable.PrettyTable(field_names=field_names)
        for r in self.rows:
            p.add_row(r)
        return f'{str(p)}\n(Rows {len(self.rows)})'

    def __repr__(self):
        return self.to_pretty_string()

def exec_plan(physical_plan: PhysicalOperator) -> Result:
    physical_plan.open()
    # 初始化后，columns 才会有值
    result = Result(target_columns=physical_plan.columns)
    for row in physical_plan.next():
        result.add_row(row)
    physical_plan.close()
    return result

